import { connect } from 'umi';
import { ConractControllerContext, IContractsActionEnum, useContractsReducer } from '../common';
import '../common/styles.less';
import { Col, Form, Row, Spin, message, Modal } from 'antd';
// import { UpdateViewRight } from './UpdateViewRight';
import { ContractManageAPI } from '../common/type';
import { UpdateViewLeft } from './UpdateViewLeft';
import { useEffect, useState } from 'react';
import {
  addContractService,
  editContractService,
  getMcontractByIDService,
  editRecordContractService,
  submitRecordContractService,
  addAndSubmitContractService,
} from '../services';
import { getColorTextLoadMap, getKeyRouter } from '@/utils';
import { history } from 'umi';
import { editModifyContract } from '../mconfig';
import { readReadShowFileService } from '@/services/BaseLayout';
import { QuestionCircleOutlined } from '@ant-design/icons';

const ContractUpdateView: React.FC<ContractManageAPI.IContractUpdate> = ({ curRes, locationProps }) => {
  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';

  /** 获取reducets */
  const { counterpartRows, contractTempRow, contractDispatch, contarctJsonList, materialCheckRows, partyFirstSelectRows } = useContractsReducer();

  /** 表单form */
  const [contractForm] = Form.useForm();

  /** 保存变更合同ID */
  const [modifyInfoDetail, setModifyInfoDetail] = useState<Record<string, any>>({});

  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {},
      });

      if (res?.obj?.templateID) {
        contractDispatch({
          type: IContractsActionEnum.SELECT_COUNTERTEMPLA,
          payload: {
            id: res?.obj?.templateID,
          },
        });
      }

      if (res?.obj && res?.obj?.oppositeList?.length > 0) {
        contractDispatch({
          type: IContractsActionEnum.SELECT_COUNTERPARTROWS,
          payload: res?.obj?.oppositeList,
        });
      }

      // 处理合同主体信息
      contractDispatch({
        type: IContractsActionEnum.SELECT_PARTYALIST,
        payload: [
          {
            oppositeName: res?.obj?.oppositeName,
            oppositeID: res?.obj?.id,
            // phoneMobile: res?.obj?.contactMobile,
            // contactName: res?.obj?.contactName,
            creditID: res?.obj?.creditID,
            bankName: res?.obj?.bankName,
            bankAccount: res?.obj?.bankAccount,
            registerPhone: res?.obj?.registerPhone,
            workAddress: res?.obj?.workAddress,
            partyId: `party-first-${getKeyRouter()}`,
          },
        ],
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDInfo, getMcontractByIDLoading, getMcontractByIDRun } = getMcontractByIDService(detailsCallback);

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.id) {
      getMcontractByIDRun({
        id: locationProps?.state?.id,
      });
    }
  }, [locationProps?.state?.id]);

  /** 刷新详情 */
  const reloadDetail = (id?: string) => {
    let contactId = id ? id : locationProps?.state?.id;
    if (!contactId) return;
    getMcontractByIDRun({
      id: contactId,
    });
  };

  /** 点击编辑变更解除方法 */
  editModifyContract(modifyInfoDetail, setModifyInfoDetail);

  /** 重新加载提示 */
  const { confirm } = Modal;
  const reloadContact = (msg: string) => {
    confirm({
      title: '提示',
      icon: <QuestionCircleOutlined />,
      content: msg,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        reloadDetail();
      },
      onCancel() {},
    });
  };

  /** 添加编辑回调 */
  const updateCallback = (res: any, clickType: boolean, isNeedSubmit?: boolean) => {
    if (res && res?.msgFlag) {
      if (clickType && !isNeedSubmit) {
        let params = {
          pageType: 'add',
          id: res?.obj?.id,
          delRouterName: history.location.pathname, //必传,要删除的路由名称
          updateType: locationProps?.state?.updateType,
          returnPathName: locationProps?.state?.returnPathName,
        };
        history.push({
          pathname: `/contractController/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: params,
        });
        // if (locationProps?.state?.updateType == 'UpdateRepairAdd') {
        //   history.push({
        //     pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
        //     state: {
        //       pageType: 'detail',
        //       id: res?.obj?.id,
        //       pageInfo: res?.obj,
        //       pIDDetailInfo: {
        //         ...res?.obj,
        //       },
        //       delRouterName: history.location.pathname, //必传,要删除的路由名称
        //     },
        //   });
        // } else {
        //   history.push({
        //     pathname: `/contractController/edit/:${getKeyRouter()}${getKeyRouter()}`,
        //     state: {
        //       pageType: 'add',
        //       id: res?.obj?.id,
        //       delRouterName: history.location.pathname, //必传,要删除的路由名称
        //     },
        //   });
        // }
      } else {
        message.success(res?.msg);
        reloadDetail(res?.obj?.id);
      }
    } else {
      if (!res?.versionFlag) {
        reloadContact(res?.msg);
      }
      message.error(res?.msg);
    }
  };

  /** 添加接口 */
  const { addContractLoading, addContractRun } = addContractService(updateCallback, locationProps?.state?.updateType);

  const { addAndSubmitContractLoading, addAndSubmitContractRun } = addAndSubmitContractService(updateCallback, locationProps?.state?.updateType);

  /** 补录编辑接口 */
  const { editRecordContractLoading, editRecordContractRun } = editRecordContractService(updateCallback);

  /** 补录提交接口 */
  const { submitRecordContractLoading, submitRecordContractRun } = submitRecordContractService(updateCallback);

  /** 编辑接口 */
  const { editContractLoading, editContractRun } = editContractService(updateCallback);

  /** 轻阅读预览 */
  const { readReadShowFileRun, readReadShowFileLoading } = readReadShowFileService();

  return (
    <ConractControllerContext.Provider
      value={{
        styleFixCls,
        curRes,
        locationID: locationProps?.state?.id,
        contractDispatch,
        pageType: locationProps?.state?.pageType,
        counterpartRows,
        materialCheckRows,
        contractTempRow,
        contractForm,
        contractDetailInfo: {
          ...getMcontractByIDInfo,
          supplyTypeName: getColorTextLoadMap(getMcontractByIDInfo?.supplyTypeName)?.colorText,
          procureRealName: getColorTextLoadMap(getMcontractByIDInfo?.procureRealName)?.colorText,
        },
        contarctJsonList,
        reloadDetail,
        updteAddOrEdit: {
          addContractRun,
          editContractRun,
          editRecordContractRun,
          submitRecordContractRun,
          addContractAttachRun: () => {},
          addAndSubmitContractRun,
        },
        oldContractForm: {},
        oldContractInfo: {},
        locationState: locationProps?.state,
        getDetailInfoRun: () => {},
        partyFirstSelectRows,
        readReadShowFileRun,
      }}
    >
      <Spin
        spinning={
          getMcontractByIDLoading ||
          addContractLoading ||
          editContractLoading ||
          readReadShowFileLoading ||
          editRecordContractLoading ||
          submitRecordContractLoading ||
          addAndSubmitContractLoading
        }
      >
        <Row gutter={[8, 8]} className={`${styleFixCls}row`}>
          <Col span={24} className={`${styleFixCls}row-col`}>
            <UpdateViewLeft />
          </Col>
        </Row>
      </Spin>
    </ConractControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(ContractUpdateView);
